package com.example.springbootlearn.netty;

import cn.hutool.json.JSONUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class St {

    private static Map<String, Channel> map = new ConcurrentHashMap<>();

    // todo 存储channel
    public static void put(String key, Channel value) {
        log.info("存储的key为：{}，value为：{}", key, value.id().asShortText());
        map.put(key, value);
    }

    // send message to channel
    public static void send(String key, Object message) {
        Channel channel = map.get(key);
        if (channel != null) {
            log.info("发送消息到channel：{}，消息为：{}", channel.id().asShortText(), message);
            channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(message)));
        }
    }

    public static void remove(String messageId) {
        Channel remove = map.remove(messageId);
        if (remove != null) {
            log.info("移除的channel：key为：{}，value为：{}", messageId, remove.id().asShortText());
        }
    }

    // get all channel
    public static Object getMap() {
        return map.keySet();
    }
}
